<!-- eslint-disable no-undef -->
<script setup lang="ts">
import {
  reqAddPatient,
  reqDelPatient,
  reqGetPatientList,
  reqUpdatePatient
} from '@/services/patient'
import type { PatientType } from '@/types/patient'
import { ref, computed, watch, nextTick } from 'vue'
import { NameRules, IdRules } from '@/utils/rules'
import {
  showSuccessToast,
  showToast,
  type FormInstance,
  showConfirmDialog
} from 'vant'
import useStore from '@/stores'
const { consult } = useStore()
const patientList = ref<PatientType[]>([])
// 获取患者列表
const getList = async () => {
  const res = await reqGetPatientList()
  patientList.value = res.data
  // 取到患者列表后 做默认选中
  defaultCheck()
}
getList()

// 不要准备简单的数组包字符串的数据
const options = [
  {
    label: '女',
    value: 0
  },
  {
    label: '男',
    value: 1
  }
]
const gender = ref(0)
// 弹出层展示布尔值
const show = ref(false)
// 弹出层表单关联的数据
const patient = ref<PatientType>({
  name: '',
  idCard: '',
  gender: 0,
  defaultFlag: 1
})
// 让默认就诊人关联这个计算属性, 这个计算属性返回一个布尔值
const defaultFlag = computed({
  get() {
    return patient.value.defaultFlag ? true : false
  },
  set(v) {
    patient.value.defaultFlag = v ? 1 : 0
  }
})
const formRef = ref<FormInstance | null>(null)
// 侦听show属性的变化, false的是重置表单
watch(
  () => show.value,
  (v) => {
    if (!v) {
      // 重置校验提示
      // console.log(formRef.value)
      // 重置表单
      patient.value = {
        name: '',
        idCard: '',
        gender: 0,
        defaultFlag: 1
      }
      console.log(1)
      nextTick(() => {
        // console.log(formRef.value)
        formRef.value?.resetValidation()
      })
    }
  }
)
// 点击保存按钮的处理函数
const handleSubmit = async () => {
  // 1. 预校验
  await formRef.value?.validate()
  // 2. 验证身份性别  身份证倒数第二位 偶数是女 奇数是男
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) return showToast('身份信息和性别不符')
  // 3. 发送请求
  //
  patient.value.id
    ? await reqUpdatePatient(patient.value)
    : await reqAddPatient(patient.value)

  // 4. 提示
  showSuccessToast(patient.value.id ? '编辑成功' : '添加成功')
  // 5. 关闭弹出层
  show.value = false
  // 6. 重新获取患者列表
  getList()
}
// 点击编辑按钮回显
const showEdit = (item: PatientType) => {
  // console.log(item)
  const { name, id, idCard, gender, defaultFlag } = item
  // 1. 展示对话框
  show.value = true
  // 2. 将患者信息回显
  patient.value = { name, id, idCard, gender, defaultFlag }
}

// 删除患者
const del = async () => {
  // 1. 确认提示
  const str = await showConfirmDialog({
    title: '温馨提示',
    message: '你确定删除该患者么'
  }).catch(() => {})
  if (str === 'confirm') {
    // 2. 发送请求
    await reqDelPatient(patient.value.id as string)
    // 3. 提示
    showSuccessToast('删除成功')
    // 4. 关闭弹出层
    show.value = false
    // 5. 重新获取
    getList()
  }
}
const route = useRoute()
// console.log(route.query.isChange)
// 计算 属性控制显示极速问诊元素
const isChange = computed(() => route.query.isChange === '1')

//点击切换高亮(切换类名) 选中的患者id
const patientId = ref<string>()
// 页面加载完毕后, 为patientId赋值, 如果患者列表中有人是默认状态,记录他的id
const defaultCheck = () => {
  const o = patientList.value.find((item) => item.defaultFlag)
  // 记录有默认标识的高亮
  if (o) {
    patientId.value = o.id
  } else {
    // 指定第一个人高亮
    patientId.value = patientList.value[0]?.id
  }
}
const router = useRouter()
// 收集患者id下一步
const next = () => {
  // 1. 空值校验
  if (!patientId.value) return showToast('请选择一位患者')
  // 2.存储患者id到仓库
  consult.setPatientId(patientId.value)
  // 3.跳转页面
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        v-for="item in patientList"
        :key="item.id"
        @click="patientId = item.id"
        :class="{ selected: patientId === item.id }"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{
            item.idCard.replace(/^(.{6}).+(.{4})$/, '\$1********\$2')
          }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon" @click="showEdit(item)">
          <cp-icon name="user-edit" />
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <div
        class="patient-add"
        v-if="patientList.length < 6"
        @click="show = true"
      >
        <cp-icon name="user-add" />
        <p>添加患者 {{ defaultFlag }}</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
    <!-- 测试单选组件 -->
    <!-- <cp-radio-btn :options="options" v-model="gender"></cp-radio-btn> -->
    <!-- 新增患者/编辑患者弹出层 -->
    <van-popup
      v-model:show="show"
      position="right"
      style="width: 100%; height: 100%"
    >
      <cp-nav-bar
        :title="patient.id ? '编辑患者' : '添加患者'"
        right-text="保存"
        :back="() => (show = false)"
        @handle-click-right="handleSubmit"
      ></cp-nav-bar>
      <!-- 表单 -->
      <van-form autocomplete="off" ref="formRef">
        <van-field
          label="真实姓名"
          v-model="patient.name"
          placeholder="请输入真实姓名"
          :rules="NameRules"
        />
        <van-field
          label="身份证号"
          v-model="patient.idCard"
          placeholder="请输入身份证号"
          :rules="IdRules"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn
              v-model="patient.gender"
              :options="options"
            ></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox :icon-size="18" round v-model="defaultFlag" />
          </template>
        </van-field>
      </van-form>
      <!-- 按钮 -->
      <van-action-bar v-if="patient.id">
        <van-button type="danger" plain block round @click="del"
          >删除</van-button
        >
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

.patient-page {
  padding: 46px 0 80px;
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
</style>
